import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { salaryUrl } from '@/utils/requestUrl'
// import CryptoJS from 'crypto-js'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: salaryUrl,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})
service.defaults.timeout=600000
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent base64加密
    const date4base64 = false // false
    let isupload = false
    if (Object.prototype.hasOwnProperty.call(config, 'type')) {
      if (config.type === 'upload') {
        isupload = true
      }
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    //  console.log(config.data)
    // config.method === 'post'
    //     ? config.data = JSON.stringify({...config.data})
    //     : config.params = {...config.params}
    // 判断是否需要加密
    // const pob = { ...config.params }
    // const ob = JSON.parse(JSON.stringify({ ...config.data }))
    // const map = new Map()
    if (date4base64) {
      const Base64 = require('js-base64').Base64
      if (isupload) {
        console.info(isupload)
      } else {
        if (config.method === 'post') {
          config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        }

        config.method === 'post'
          ? config.data = Base64.encode(JSON.stringify(config.data))
          : config.params = { encry: Base64.encode(JSON.stringify({ ...config.params })) }
      }
      // console.log(config.data)

      // Object.keys(ob).forEach(function(key) {
      //   ob[key] = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(ob[key]))
      // })
      // config.data = JSON.stringify(ob)

      // Object.keys(pob).forEach(function(key) {
      //   pob[key] = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(pob[key]))
      // })
      // config.params = pob
    }
    // console.log(pob)
    // console.log(config.data)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (Object.prototype.hasOwnProperty.call(res, 'rscode')) {
      if (res.rscode !== '100000' && res.rscode !== '113999') {
        Message({
          showClose: true,
          dangerouslyUseHTMLString: true,
          message: res.result || 'Error',
          type: 'error',
          duration: 0
        })
        return Promise.reject(new Error(res.result || 'Error'))
      } else if (res.rscode === '113999') { // token失效，跳转到平台
        const result = JSON.parse(res.result)
        location.href = result.redirectPath
        return Promise.reject(new Error('Error'))
      } else {
        return res
      }
    } else {
      return res
    }
  },
  error => {
    Message({
      showClose: true,
      message: error.message,
      type: 'error',
      duration: 0
    })
    return Promise.reject(error)
  }
)

export default service
